<?php

class TableauArchitecteController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view', 'pdf', 'testPdf','ExcelPubliPost'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'expression' => 'isset(Yii::app()->user->canEdit) && Yii::app()->user->canEdit'
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
			'equipes' => Equipe::model()->with('architecte', 'bureauxEtude')->findAllByAttributes( array('idTableauArchitecte' => $id) )
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new TableauArchitecte;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['TableauArchitecte']))
		{ 
			$model->attributes=$_POST['TableauArchitecte'];
			
			// définition des valeurs automatiques
			$model->utiCreateur = Yii::app()->user->username;
			$model->dateCreation = date('Y-m-d H:i:s');
			
			if($model->save())
				$this->redirect(array('view','id'=>$model->idTableauArchitecte));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['TableauArchitecte']))
		{ 
			$model->attributes=$_POST['TableauArchitecte'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->idTableauArchitecte));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model=new TableauArchitecte('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['TableauArchitecte']))
			$model->attributes=$_GET['TableauArchitecte'];

		$this->render('index',array(
			'model'=>$model,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new TableauArchitecte('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['TableauArchitecte']))
			$model->attributes=$_GET['TableauArchitecte'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return TableauArchitecte the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=TableauArchitecte::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param TableauArchitecte $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='tableau-architecte-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	 * Génère le pdf
	 * @param integer $id identifiant du tableau d'architectes
	 */
	public function actionPdf($id) {

		$html2pdf = Yii::app()->ePdf->HTML2PDF('L', 'A3', 'fr');
		
		$model = $this->loadModel($id);
		
		$html2pdf->pdf->SetTitle($model->nom);
		
		$html = $this->renderPartial('pdf',array(
			'model'=>$model,
                        'obs'=> isset($_GET['obs'])?true:false,
			'equipes' => Equipe::model()->findAllByAttributes( array('idTableauArchitecte' => $id) ),
		), true);
		
		$html2pdf->WriteHTML($html);
		
		$html2pdf->Output($model->nom.'.pdf', 'I');
	}

	public function actionTestPdf ( $id ) { 
		$model = $this->loadModel($id);
		$this->render('pdf',array(
			'model'=>$model,
			'equipes' => Equipe::model()->findAllByAttributes( array('idTableauArchitecte' => $id) ),
		));
	}
        
        /**
	 * Génère un excel reprenant chaque nom d’architecte + le n° de l’équipe correspondant
         * ensuite ce fichier pour créer un tableau de votes qu'y est rempli manuellement en commission 
	 * @param integer $id identifiant du tableau
	 */
	public function actionExcelPubliPost($id) {
		
		// on recherche le tableau
		$model = $this->loadModel($id);
		
		// on rechercle les équipe associés au tableau
                $equipes = Equipe::model()->findAllByAttributes( array('idTableauArchitecte' => $id) );
		
                // on importe les composants du module
		Yii::import('EExcelWriter.components.EExcelWriter');
		Yii::import('EExcelWriter.vendors.*');
		
                $dataProvider = new CArrayDataProvider($equipes,
                            array(
                                'pagination' => array(
                                    'pageSize' => 5000000, // large number so you export all to excel
                                ),
                            )
                        );

		// on crée notre excel
		$this->widget('EExcelWriter', array(
				'dataProvider' => $dataProvider,
				'title'        => 'blabla titre',
				'stream'       => true,
				'fileName'     => 'excels/'. $model->idTableauArchitecte .'_publipostage.xls',
				'columns'      => array(
					array(
						'header' => "NOM",
						'value' => 'mb_convert_encoding(Entreprise::model()->findByPk($data->idArchitecte)->nom,"","utf-8")',// pour éviter les problèmes d'encodage
					),
					array(
						'header' => "RUE",
						'value' => 'mb_convert_encoding(Entreprise::model()->findByPk($data->idArchitecte)->rue,"","utf-8")', 
					),
					array(
						'header' => "Commune",
						'value' => 'Entreprise::model()->findByPk($data->idArchitecte)->commune', 
					),
					array(
						'header' => "CP",
						'value' => 'Entreprise::model()->findByPk($data->idArchitecte)->cp', 
					),
					array(
						'header' => "Civilite",
						'value' => 'Entreprise::model()->findByPk($data->idArchitecte)->civilite', 
					)
                                    
				),
		));
	}
}
